import os
import sys
import cv2
import shutil
import corecode
import numpy as np
np.set_printoptions(threshold=32, edgeitems=10)
try:
   import cPickle as pickle
except:
   import pickle
#Loads an image.
sys1 = sys.argv[1]
cv_i = cv2.imread(sys1)

#Standardizes an image
if sys1 is None:
        print 'Not an image'
        sys.exit(1)
if str(type(cv_i)) == "<type 'NoneType'>":
        print 'Not an image'
        sys.exit(1)
if cv_i.shape[1] < 256:
        print 'This script is for getting storing high-resolution face encodings'
        print 'Please select a higher-resolution face.'
        sys.exit(1)

#Gets the embeddding.
img1 = corecode.load_image_file(sys1)
fen0 = corecode.face_encodings( img1)
fen1 = corecode.face_encodings( img1)[0]

#Ensures there's only one embedding.
if len(fen0) > 1:
        print 'This script is for storing the embeddings from a single face only'
        print 'Please select a single face.'
        sys.exit(1)

#Get's the person's name
f_name = raw_input("This person's first name: ")
l_name = raw_input("This person's last  name: ")
name = ("{}.{}".format(f_name.lower(),l_name.lower()))

#Makes that person's folder. 
def makeFolder(n):
	folder = ((os.getcwd()) + "/embeddings/" + n + "/")
	if not os.path.exists(folder): os.makedirs(folder)
	return folder
e_f = makeFolder(name)

#Simple filecount function.
def  filecount(DIR): 
     return len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])

#Checks if this is a new face....
cInt = filecount(e_f)
if cInt < 2:
   fID = str(cInt + 1).zfill(4)
   with open(e_f + "/{}_mainEm.{}_".format(str(fID),name) + ".pickle",'wb') as pf: 
        pickle.dump(fen1, pf)
   fex = str(sys1).split('.')[-1]
   shutil.copy(sys1, e_f + "/{}_mainPk.{}_.".format(str(fID),name) + fex)

else: #Or an old one.
   tInt = (cInt/3)
   print ("AdId #{}".format(tInt))
   fID = str(tInt + 1).zfill(4)
   with open(e_f + "/{}_ad_mainEm.{}_".format(str(fID),name) + ".pickle",'wb') as pf: 
        pickle.dump(fen1, pf)
   fex = str(sys1).split('.')[-1]
   shutil.copy(sys1, e_f + "/{}_ad_mainPk.{}_.".format(str(fID),name) + fex)

